#!/usr/bin/python
# -*- encoding:utf-8 -*-

"""
    提供对外加密/解密的接口
    previous preparation:
        pip install cryptography -i https://mirrors.aliyun.com/pypi/simple/
    （https://pypi.org/project/cryptography/）
    offical declaration:
        It supports Python 2.7, Python 3.6+, and PyPy 5.4+.
"""
import sys

sys.path.append("..")
from fastapi import FastAPI
import uvicorn
from pydantic import BaseModel  # fastapi的一个依赖,需要从pydantic中引入
from sftp_account_manage.com.util.Encrypt1 import Encrypt

app = FastAPI()


class Payloads(BaseModel):  # 继承BaseModel
    operate_type: str  # 加密'encode'/解密'decode'
    auto_generate_key: bool = True  # 默认使用自动生成(Fernet key must be 32 url-safe base64-encoded bytes)
    decrypt_key: str = None  # 解密时使用的密匙
    secret_str: str  # 需要加密或者解密的串
    """
        载荷参数示例：
        1.加密（自动生成密匙串）
{
    "operate_type": "encode",
    "secret_str": "who are you?"
}
        2.解密（参数需要带上密匙，密匙会在加密时返回）
{
    "operate_type": "decode",
    "decrypt_key": "GOmqTysJTtcq1IFOO7H7qyzUOz0Y1eX_rmLKTBSOo90",
    "secret_str": "gAAAAABf6_95LLop8y_egjOKlF7UyzUjlpJL5Pv9vNSHpLLetOB1CjrLa7ukta7Y1QmclWbmuSyK-WUgAwAo_h50kXT_vqhZbg=="
}
    """


@app.post("/aes_encrypt")  # get不支持请求体,更换请求方法
async def postEchoApi(args: Payloads):  # 设置刚才定义的参数
    rbody = {'msg': '请求参数有误,请检查后重试', 'statusCode': -1}
    if args.operate_type == "encode" and args.auto_generate_key:
        e = Encrypt()
        token = e.get_encrypt_str(e.str_to_bytes(args.secret_str))
        key = e.key
        rbody['msg'] = '密文获取成功，请注意保留对称加密密匙'
        rbody['statusCode'] = 1
        rbody['token'] = token
        rbody['key'] = key
    elif args.operate_type == "decode":
        e = Encrypt()
        if args.decrypt_key == '':
            rbody['msg'] = '密匙不可为空,请检查后重试'
            return rbody
        e.set_key(e.str_to_bytes(args.decrypt_key))
        text = e.get_decrypt_str(e.str_to_bytes(args.secret_str))
        if text == '':
            rbody['msg'] = '解密失败，密匙或密文不正确'
            return rbody
        key = e.key
        rbody['msg'] = '密文解密成功，请注意保留对称加密密匙'
        rbody['statusCode'] = 1
        rbody['text'] = text
        rbody['key'] = key
    return rbody


if __name__ == '__main__':
    args = sys.argv
    """
        In linux:
        (Run command 1): nohup python3 encrypt_manage.py -p 8086 > $Project_Absolute_Path/logs/encrypt_manage.log 2>&1 &
        (Run command 2): cd $Project_Absolute_Path 
                         nohup python3 encrypt_manage.py -p 8086 > ./logs/encrypt_manage.log 2>&1 &
            args[0], encrypt_manage.py
            args[1], -p
            args[2], 8080
        (Check run status): ps -ef | grep -v grep | grep encrypt_manage.py | awk '{print $2}'
        (Count run process): ps -ef | grep -v grep | grep encrypt_manage.py | wc -l
        (Kill this process): ps -ef | grep -v grep | grep encrypt_manage.py | awk '{print $2}' | xargs kill -9
    """
    if len(args) == 3 and args[0] == 'encrypt_manage.py' and args[1] == '-p':
        try:
            port = int(args[2])
            uvicorn.run(app=app,
                        host="0.0.0.0",
                        port=port,
                        workers=1)
        except BaseException as e:  # 如果发生异常，例如端口占用，则返回False
            print('端口号设置有误，请更正(', e, ')')
    else:
        print('启动方式不正确, The correct startup way should like【python encrypt_manage.py -p 8081】')
